#include "Player.h"

#include<QTimer>

#include"Playlist.h"
#include"SimplePlayer.h"

#include"Song.h"

Player::Player(QObject *parent):QObject(parent){
	m_desiredState = Stopped;

	m_stateTimer = new QTimer(this);
	connect(m_stateTimer, SIGNAL(timeout()), this, SLOT(slotStateTimerTimeout()));

	m_simplePlayer = new SimplePlayer(this);
	connect(m_simplePlayer, SIGNAL(finished(QUrl)), this, SLOT(slotPlayerFinished()));

	m_playlist = new Playlist;
}

Player::~Player(){
//All cleanup should be done by Qt
}

void Player::slotPlayerFinished(short attempts){
	printf("Player::slotPlayerFinished()\n");
	if(m_desiredState != Playing)
		return;

	if(m_playlist->next()){
		if(m_playlist->current())
			m_simplePlayer->play(m_playlist->current()->data()->path);
		else if(attempts)
			slotPlayerFinished(attempts-1);
	}else{
		m_desiredState = Stopped;
		emit stopped();
	}
}

/*void Player::play(int seqNo){
	emit playing();
	m_desiredState = Playing;
	if(Song *song = m_playlist->songAt(seqNo)){
		m_simplePlayer->play(song->data()->path);
		m_playlist->setAt(seqNo);
	}
	m_stateTimer->start(STATE_CHECK_TIMER);
}*/

void Player::play(){
	printf("Player::play()\n");
	emit playing();
	m_desiredState = Playing;
	if(m_playlist->current())
		m_simplePlayer->play();
	else if(m_playlist->next())
		if(m_playlist->current())
			m_simplePlayer->play(m_playlist->current()->data()->path);
	m_stateTimer->start(STATE_CHECK_TIMER);
}

void Player::pause(){
	emit paused();
	m_desiredState = Paused;
	m_simplePlayer->pause();
	m_stateTimer->start(STATE_CHECK_TIMER);
}

void Player::stop(){
	emit stopped();
	m_desiredState = Stopped;
	m_simplePlayer->stop();
	m_stateTimer->start(STATE_CHECK_TIMER);
}

void Player::next(){
	emit playing();
	printf("Player::next()\n");
	m_desiredState = Playing;
	if(m_playlist->next())
		if(m_playlist->current())
			m_simplePlayer->play(m_playlist->current()->data()->path);
	m_stateTimer->start(STATE_CHECK_TIMER);
}

void Player::prev(){
	emit playing();
	m_desiredState = Playing;
	if(m_playlist->prev())
		if(Song *song = m_playlist->current())
			m_simplePlayer->play(song->data()->path);
	m_stateTimer->start(STATE_CHECK_TIMER);
}

void Player::slotStateTimerTimeout(){
	switch(m_desiredState){
		case Playing:
			if(m_simplePlayer->state() != SimplePlayer::Playing && m_simplePlayer->state() != SimplePlayer::Loading)
				play();
			else
				emit playing();
			break;
		case Paused:
			if(m_simplePlayer->state() == SimplePlayer::Playing || m_simplePlayer->state() == SimplePlayer::Loading)
				m_simplePlayer->pause();
			else{
				m_stateTimer->stop();
				emit paused();
			}
			break;
		case Stopped:
			if(m_simplePlayer->state() == SimplePlayer::Playing || m_simplePlayer->state() == SimplePlayer::Loading)
				m_simplePlayer->stop();
			else{
				m_stateTimer->stop();
				emit stopped();
			}
			break;
	}
}
